﻿#include "EditorFolderAbilityModel.h"

#include "Framework/Editor.h"
#include "Project/ProjectModel.h"


void REditorFolderAbilityModel::FirstTimeInitializeObject()
{
    Super::FirstTimeInitializeObject();

    auto ProjectInfo=REditor::Get()->GetSubsystem<RProjectModel>()->GetCurrentProjectInfo();
    if(ProjectInfo.HasValue())
    {
        SetRootFolder(ProjectInfo.GetValue().Path);
    }

    REditor::Get()->GetSubsystem<RProjectModel>()
        ->OnProjectOpened.BindScript(
            this
            ,&REditorFolderAbilityModel::OnProjectOpened);

}

CString REditorFolderAbilityModel::GetName() const
{
    if(RootFolder.IsEmpty())
    {
        return U"未设置根目录";
    }
    else
    {
        return RootFolder.GetFileOrDirectoryName();
    }
}

SPath REditorFolderAbilityModel::GetRootFolder() const
{
    return RootFolder;
}

void REditorFolderAbilityModel::SetRootFolder(const SPath &InRootFolder)
{
    if(RootFolder==InRootFolder)
    {
        return;
    }

    RootFolder = InRootFolder;
    OpenedFolders.Resize(1);
    OpenedFolders[0]=InRootFolder;
    OnRootFolderChanged.ExecuteIfBound();
}

TVector<SPath> REditorFolderAbilityModel::GetOpenedFolders() const
{
    return OpenedFolders;
}

void REditorFolderAbilityModel::CloseFolder(const SPath &InFolder)
{
    OpenedFolders.Remove(InFolder);
    OnFolderOpenStateChanged.ExecuteIfBound(InFolder,false);
}

void REditorFolderAbilityModel::CloseAllFolders()
{
    if(OpenedFolders.Num()>1)
    {
        auto OldOpenedFolders=OpenedFolders;
        OpenedFolders.Resize(1);
        for(int i=1;i<OldOpenedFolders.Num();i++)
        {
            OnFolderOpenStateChanged.ExecuteIfBound(OldOpenedFolders[i],false);
        }
    }
}

void REditorFolderAbilityModel::OpenFolder(const SPath &InFolder)
{
    if(!IsFolderOpened(InFolder))
    {
        OpenedFolders.Add(InFolder);
        OnFolderOpenStateChanged.ExecuteIfBound(InFolder,true);
    }
}

bool REditorFolderAbilityModel::IsFolderOpened(const SPath &InFolder) const
{
    return OpenedFolders.Contains(InFolder);
}

void REditorFolderAbilityModel::OnProjectOpened()
{
    auto ProjectInfo=REditor::Get()->GetSubsystem<RProjectModel>()->GetCurrentProjectInfo();
    assert(ProjectInfo.HasValue());
    SetRootFolder(ProjectInfo.GetValue().Path);    
}
